	//
//  MedicineListTableViewController.m
//  myMedicine1.0
//
//  Created by pollysoft on 16/8/2.
//  Copyright © 2016年 microi. All rights reserved.
//

#import                                                      "MedicineListTableViewController.h"
#import                                                      "MedicineListTableViewCell.h"
#import                                                      "eatMedicineOfNumberTableViewCell.h"
#import                                                      "CoreData/CoreData.h"
#import                                                      "DrugMasterEntity+CoreDataProperties.h"
#import                                                      "DrugMasterEntity.h"
#import                                                      "AppDelegate.h"
#import                                                      "indexPathOfbarButtonItem.h"
#import                                                      "noteTableViewCell.h"
#import                                                      "DrugFlowingEntity.h"
#import                                                      "DrugFlowingEntity+CoreDataProperties.h"
#define addPhotoCellId                                       @"MedicineListTableViewCell"
#define rightDetailCellId                                    @"rightDetailCell"
#define MedicineNumberCellId                                 @"MedicineNumberCell"
#define MedicineNoteCellId                                   @"MedicineNoteCell"
#define SCREEN [UIScreen                                     mainScreen].bounds.size
@interface MedicineListTableViewController                   ()<MedicineListDelegate,eatMedicineOfNumberDalegate,UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (weak, nonatomic) MedicineListTableViewCell        *addPhotoCell;
@property (weak, nonatomic) eatMedicineOfNumberTableViewCell *MedicineNumberCell;
@property (weak, nonatomic) noteTableViewCell                *noteCell;
@property(strong, nonatomic) UIImage                         *medicineImage;
@property (strong, nonatomic) NSString                       *remind;
@property (nonatomic, strong) UIView                         *fatherView;                                                                                                                     // 传入的父控件, 确定datePicker往哪儿加
@property (strong, nonatomic) DrugMasterEntity               *drugMaster;
@property (nonatomic, strong) DrugFlowingEntity *drugFlowing;
@property (strong, nonatomic) UIButton                       *bottomButton;
@property (assign, nonatomic) NSInteger                      offsetY;
@property (strong, nonatomic) indexPathOfbarButtonItem       *doneBtn;
@property (nonatomic, assign) NSInteger eatMedicineNumber;
@property (nonatomic, strong) NSDateFormatter *timeFormatter;
@property (nonatomic, strong) NSDateFormatter *dateFormatter;
@property (nonatomic, strong) NSFetchedResultsController *fetchedController;
@end

@implementation MedicineListTableViewController
{
    UIDatePicker *datePicker;
    UIToolbar *toolBar;
    AppDelegate *app;

}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.fatherView];
    [self.view sendSubviewToBack:self.fatherView];
    self.tableView.dataSource                                = self;
    self.tableView.delegate                                  = self;
//    [self.tableView reloadData];

    app                                                      = [UIApplication sharedApplication].delegate;

    //添加底部按钮
    [self addFooterButton];
    
    if (self.eatMedicineNumber == 0) {
            self.eatMedicineNumber = 2;
    }

    //这次改了没
    
    
}


/**
 *  添加底部按钮
 */
-(void)addFooterButton
{
    //1.初始化Button
    self.bottomButton                                        = [UIButton buttonWithType:UIButtonTypeCustom];

    //2.设置文字和文字颜色
    [self.bottomButton setTitle:@"确认修改" forState:UIControlStateNormal];
    [self.bottomButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

//    //3.设置圆角幅度
//    self.bottomButton.layer.cornerRadius = 10.0;
//    self.bottomButton.layer.borderWidth = 1.0;

    //4.设置frame
    self.bottomButton.frame                                  = CGRectMake(0, SCREEN.height -50 - 44 - 20, SCREEN.width, 50);

    //5.设置背景色
    self.bottomButton.backgroundColor                        = [UIColor orangeColor];

    //6.设置触发事件
    [self.bottomButton addTarget:self action:@selector(ConfirmTheChangeAction) forControlEvents:UIControlEventTouchUpInside];

    //7.添加到tableView tableFooterView中
    [self.view addSubview: self.bottomButton];



}
#pragma mark – ConfirmTheChangeAction
-(void)ConfirmTheChangeAction{

    
    // 通过上下文保存对象，并在保存前判断是否有更改
    NSError *error                                           = nil;
    if (app.managedObjectContext.hasChanges) {
        [app.managedObjectContext save:&error];
    }
    NSLog(@"看这error%@",error);
    // 错误处理
    if (error) {
        NSLog(@"CoreData Insert Data Error : %@", error);
    }


}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark – MedicineListTableViewCell的代理方法
-(void)presentSellectPhotocontroller:(UIViewController *)viewController  and:(NSIndexPath *) indexPath{

    if (indexPath.section == 0) {
    UIAlertController *alertController                       = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancelAction                              = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

        }];
    UIAlertAction *fromPhotoAction                           = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            //新建一个图片控制器
    UIImagePickerController *MedicineImagePickerController   = [[UIImagePickerController alloc]init];

            //声明数据来源是图库
    UIImagePickerControllerSourceType photoLibrarySourchType = UIImagePickerControllerSourceTypePhotoLibrary;

    MedicineImagePickerController.sourceType                 = photoLibrarySourchType;
    MedicineImagePickerController.modalTransitionStyle       = UIModalTransitionStyleCoverVertical;
            //允许做图片修改
    MedicineImagePickerController.allowsEditing              = YES;
    MedicineImagePickerController.delegate                   = self;
            [self presentViewController:MedicineImagePickerController animated:YES completion:^{

            }];
        }];
    UIAlertAction *fromCameraAction                          = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
    UIImagePickerController *imagePicker                     = [[UIImagePickerController alloc]init];
    imagePicker.delegate                                     = self;
    imagePicker.allowsEditing                                = YES;
    imagePicker.modalTransitionStyle                         = UIModalTransitionStyleCoverVertical;
    imagePicker.sourceType                                   = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:imagePicker animated:YES completion:nil];
            }

        }];

        [alertController addAction:cancelAction];
        [alertController addAction:fromPhotoAction];
        [alertController addAction:fromCameraAction];

        [self presentViewController:alertController animated:YES completion:^{

        }];

    }

}

#pragma mark – eatMedicineOfNumberTableViewCell的代理方法

-(void)refreshEatMedicineOfNumber:(NSInteger) number and:(NSIndexPath *) indexPath{

    
            self.eatMedicineNumber = number;
    
             // 刷新section
                NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:2];
                [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
    

}

#pragma mark – imagePick
//用户点取消时调用
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{

}
//当用户选取完成时调用
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{

    self.medicineImage                                       = info[UIImagePickerControllerOriginalImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSLog(@"图片是%@",self.medicineImage);

    //设置相册里面选择的图片

    [self.addPhotoCell.addMedicineImageButton setImage:self.medicineImage forState:UIControlStateNormal];
    //    [cell.addMedicineImageButton setBackgroundImage:_medicineImage forState:UIControlStateNormal];

}

#pragma mark - Table view data source

//tableview滚动时触发
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{



   // _bottomButton.frame = CGRectMake(0, SCREEN.height -50 - 44 - 20, SCREEN.width, 50);
    self.bottomButton.frame                                  = CGRectMake(0, self.tableView.contentOffset.y +SCREEN.height -50,SCREEN.width, 50);
    [self.view bringSubviewToFront:self.bottomButton];



}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 4
    ;
}

//设置每个分组下tableview的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else if(section == 1){
        return 2;
    }

    else if (section == 2){
        
       return self.eatMedicineNumber + 1;
    }
    else if(section == 3){

        return 2;
    }
    return 0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *rightDetailCell                         = [tableView dequeueReusableCellWithIdentifier:rightDetailCellId ];

    
    if (!rightDetailCell) {
    rightDetailCell                                          = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:rightDetailCellId ];
    }

    //使用coredata查询数据
    
    NSManagedObjectContext *context                          = [app managedObjectContext];
    //查询DrugMasterEntity表格
    //根据表格名字找到要查询的表格
    NSEntityDescription *drugMasterEntity                              = [NSEntityDescription entityForName:@"DrugMasterEntity" inManagedObjectContext:app.managedObjectContext];
    //建立请求
    NSFetchRequest *drugMasterRequest                                  = [[NSFetchRequest alloc]init];
    //建立的请求是要查询哪个表格的
    [drugMasterRequest setEntity:drugMasterEntity];
    NSError *error = nil;
    //遍历所有的主药物表的信息，存放在数组drugMasterEntitys里面
    NSArray <DrugMasterEntity *> *drugMasterEntitys = [context executeFetchRequest:drugMasterRequest error:&error];
    

    switch (indexPath.section) {
        case 0:{//第一个section
            if (!self.addPhotoCell) {

                //注册一个cell，复用的时候可以直接使用
                UINib *MedicineListNib;
                if (MedicineListNib == nil) {
    MedicineListNib                                          = [UINib nibWithNibName:@"MedicineListTableViewCell" bundle:nil];
                    [self.tableView registerNib:MedicineListNib forCellReuseIdentifier:addPhotoCellId];
                }

            }


    self.addPhotoCell                                        = [self.tableView dequeueReusableCellWithIdentifier:addPhotoCellId forIndexPath:indexPath];

            //委托代理给myMedicineListTableViewController

    self.addPhotoCell.medicineListDalegate                   = self;
    self.addPhotoCell.viewController                         = self;
    self.addPhotoCell.indexPath                              = indexPath;

            return self.addPhotoCell;
        }break;

        case 1:{//第二个section

            switch (indexPath.row) {

                case 0:{//第一行
    rightDetailCell.accessoryType                            = UITableViewCellAccessoryDisclosureIndicator;
    rightDetailCell.textLabel.text                           = @"提醒";
                    if (self.remind == nil) {
    self.remind                                              = @"开";
                    }
    rightDetailCell.detailTextLabel.text                     = self.remind;
                    return rightDetailCell;
                    }break;
                case 1:{//第二行


    rightDetailCell.accessoryType                            = UITableViewCellAccessoryDisclosureIndicator;

    rightDetailCell.textLabel.text                           = @"开始时间";
                    /**
                     *  array == nil 和 [array count] == 0
                     前者为true的时候表示这个对象是nil，是一个空的指针，它甚至没有被创建出来。
                     后者为true表示这个对象为nil或者没有任何元素。
                     */
                    
//                    设置谓词过滤条件
//                    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"startAt"];
//                    drugMasterRequest.predicate = predicate;

 
                    //datapick没有设置开始日期
                    if (self.drugMaster.startAt == nil) {
                        //遍历数组drugMasterEntitys的每一个实例
                        [drugMasterEntitys enumerateObjectsUsingBlock:^(DrugMasterEntity * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                            
                            if (obj.startAt == nil) {//数据库中没有设置开始日期
                                rightDetailCell.detailTextLabel.text                     = @"未设置开始日期";
                            }
                            else{//数据库中有数据，直接显示数据库中的数据
                                
                                rightDetailCell.detailTextLabel.text                     = [self.dateFormatter stringFromDate:obj.startAt];
                            }
                        }];
                        return rightDetailCell;

                        
                    }else if (datePicker.date != nil){//datepick有设置时间
                        //遍历数组drugMasterEntitys的每一个实例
                        [drugMasterEntitys enumerateObjectsUsingBlock:^(DrugMasterEntity * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                            //不管数据库中有没有数据先显示datepick设置的时间
                            
                                rightDetailCell.detailTextLabel.text                     = [self.dateFormatter stringFromDate:datePicker.date];
                            
                        }];
                       return rightDetailCell;
                    }
                    
                    //错误处理
                    if (error) {
                        NSLog(@"CoreData Ergodic Data Error : %@", error);
                    }
                }break;


            }
        }break;

        case 2:{//第三个section
            
            if (indexPath.row == 0) {

                if (!self.MedicineNumberCell) {

                        //注册一个cell，复用的时候可以直接使用
                    UINib *eatMedicineOfNumberNib;
                    if (eatMedicineOfNumberNib == nil) {

    eatMedicineOfNumberNib                                   = [UINib nibWithNibName:@"eatMedicineOfNumberTableViewCell" bundle:nil];
                        [self.tableView registerNib:eatMedicineOfNumberNib forCellReuseIdentifier:MedicineNumberCellId];
                    }

                    }

    self.MedicineNumberCell                                  = [self.tableView dequeueReusableCellWithIdentifier:MedicineNumberCellId forIndexPath:indexPath];
               
                //委托代理给myMedicineListTableViewController
                
                self.MedicineNumberCell.eatMedicineOfNumberDalegate = self;
                
                self.MedicineNumberCell.indexPath                              = indexPath;
                return self.MedicineNumberCell;
            }
            else if (indexPath.row >= 1 && indexPath.row <= 8){


    rightDetailCell.accessoryType                            = UITableViewCellAccessoryDisclosureIndicator;
                
                    
                    rightDetailCell.textLabel.text                           = [NSString stringWithFormat:@"第%ld次服药",indexPath.row];
               

                return rightDetailCell;

                
            }


        }break;

        case 3:{//第四个section


            if (indexPath.row == 0) {

    rightDetailCell.accessoryType                            = UITableViewCellAccessoryDisclosureIndicator;
    rightDetailCell.textLabel.text                           = @"结束时间";


                //datapick没有设置结束日期
                if (self.drugMaster.stopAt == nil) {
                    //遍历数组drugMasterEntitys的每一个实例
                    [drugMasterEntitys enumerateObjectsUsingBlock:^(DrugMasterEntity * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        
                        if (obj.stopAt == nil) {//数据库中没有设置结束日期
                            rightDetailCell.detailTextLabel.text                     = @"未设置结束日期";
                        }
                        else{//数据库中有数据，直接显示数据库中的数据
                            
                            rightDetailCell.detailTextLabel.text                     = [self.dateFormatter stringFromDate:obj.stopAt];
                        }
                    }];
                    return rightDetailCell;
                    
                    
                }else if (datePicker.date != nil){//datepick有设置时间
                    //遍历数组drugMasterEntitys的每一个实例
                    [drugMasterEntitys enumerateObjectsUsingBlock:^(DrugMasterEntity * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        //不管数据库中有没有数据先显示datepick设置的时间
                        
                        rightDetailCell.detailTextLabel.text                     = [self.dateFormatter stringFromDate:datePicker.date];
                        
                    }];
                    return rightDetailCell;
                }
                
                //错误处理
                if (error) {
                    NSLog(@"CoreData Ergodic Data Error : %@", error);
                }
            
            

            }
            else if (indexPath.row == 1){
            //自定义一个备注的cell
                //先注册一个自定义的cell
                UINib *noteNib;
                if (!noteNib) {
    noteNib                                                  = [UINib nibWithNibName:@"noteTableViewCell" bundle:nil];
                    [self.tableView registerNib:noteNib forCellReuseIdentifier:MedicineNoteCellId];
                }

    self.noteCell                                            = [self.tableView dequeueReusableCellWithIdentifier:MedicineNoteCellId forIndexPath:indexPath];

                return self.noteCell;
            }
        }break;

    }

    return 0;

}





#pragma mark – Table View Delegate
//每一个分组下对应的tableview 高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.section == 0) {
        return 120;
    }
    return 40;
}

//设置标题内容高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 20;
    }
    return 0;
}

//设置尾部说明内容高度
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return 20;
    }
    return 0;
}
//cell选中以后的回调
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    switch (indexPath.section) {
        case 0:{//第一个section

        }break;
        case 1:{//第二个section


            switch (indexPath.row) {
                case 0:{
                    //根据cell的行数取得第二个section的cell
    UITableViewCell *cell                                    = [tableView cellForRowAtIndexPath:indexPath];
                    if ([self.remind isEqualToString:@"开"] || self.remind == nil) {

    self.remind                                              = @"关";
                    }else if([self.remind isEqualToString:@"关"]){

    self.remind                                              = @"开";

                    }
    cell.detailTextLabel.text                                = self.remind;
                }break;
                case 1:{

//                    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                    //弹出datepick
                    NSLog(@"indexPath.section && indexPath.row%ld%ld",indexPath.section,indexPath.row);
                    [self presentDataPick:indexPath];

                }break;



                default:
                    break;
            }

        }break;
        //第三个section
        case 2:{

            if (indexPath.row == 0) {
//                UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

            }else if (indexPath.row == 1){

                [self presentDataPick:indexPath];
            }


        }break;
            //第四个section
        case 3:{

            if (indexPath.row == 0) {

                [self presentDataPick:indexPath];
            }


        }break;
    }

}
#pragma mark – 弹出datapick
//弹出datapick
-(void)presentDataPick:(NSIndexPath *)indexPath{

    NSLog(@"哇擦啦2 %ld%ld",indexPath.section,indexPath.row);
    self.doneBtn.indexPath                                   = indexPath;
   if (self.fatherView &&!toolBar && !datePicker) {// 这里需要判断, 因为toolbar, datePicker你只需要建立一次, 不需要重新创建

    toolBar                                                  = [[UIToolbar alloc] initWithFrame:CGRectMake(0.f, [UIScreen mainScreen].bounds.size.height -210.f-40.f, [UIScreen mainScreen].bounds.size.width, 40.f)];
    toolBar.barStyle                                         = UIBarStyleBlackTranslucent;
    toolBar.autoresizingMask                                 = UIViewAutoresizingFlexibleHeight;
    [toolBar sizeToFit];

    self.doneBtn                                             = [[indexPathOfbarButtonItem alloc]initWithTitle:@"确定"  style:UIBarButtonItemStyleDone target:self action:@selector(doneRemove:)];
    self.doneBtn.indexPath                                   = indexPath;
    UIBarButtonItem *flexibleSpaceLeft                       = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil ];

    NSArray *array                                           = [NSArray arrayWithObjects:flexibleSpaceLeft, self.doneBtn, nil ];
    [toolBar setItems:array animated:YES];

    [self.fatherView addSubview:toolBar];
    //[_fatherView bringSubviewToFront:toolBar];

    [self showViewWithAnimation:toolBar YPostion:([UIScreen mainScreen].bounds.size.height - 210.f - 40.f)];// 出现的时候需加入动画, 根据Y轴

    datePicker                                               = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height-210.f, [UIScreen mainScreen].bounds.size.width, 210.f)];
    //设置日期显示格式为中文
    datePicker.locale                                        = [[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"];

    //设置datepick的默认时间为当天
    datePicker.calendar                                      = [NSCalendar currentCalendar];
    [datePicker setBackgroundColor:[UIColor whiteColor]];
       if (indexPath.section == 2) {
    datePicker.datePickerMode                                = UIDatePickerModeCountDownTimer;
       }else{
    datePicker.datePickerMode                                = UIDatePickerModeDate;
       }
    [self.fatherView addSubview:datePicker];
    // [_fatherView bringSubviewToFront:datePicker];
    [self showViewWithAnimation:datePicker YPostion:([UIScreen mainScreen].bounds.size.height - 210.f)];// 出现的时候需加入动画, 根据Y轴
    [self.view bringSubviewToFront:self.fatherView];
    NSLog(@"%@",@"执行成功");
        }else if ([toolBar isHidden] && [datePicker isHidden]){
            //显示
            if (indexPath.section == 2) {
    datePicker.datePickerMode                                = UIDatePickerModeTime;
            }else{
    datePicker.datePickerMode                                = UIDatePickerModeDate;
            }
            [toolBar setHidden:NO];
            [datePicker setHidden:NO];
            [self showViewWithAnimation:toolBar YPostion:([UIScreen mainScreen].bounds.size.height - 210.f - 40.f)];// 出现的时候需加入动画, 根据Y轴
            [self showViewWithAnimation:datePicker YPostion:([UIScreen mainScreen].bounds.size.height - 210.f)];// 出现的时候需加入动画, 根据Y轴
            [self.view bringSubviewToFront:self.fatherView];

        }

}
#pragma mark – 移除toolbar和datepicker
//移除toolbar和datepicker
- (void)doneRemove:(indexPathOfbarButtonItem *)sender {
    if (self.fatherView && toolBar && datePicker) {
//        NSDateFormatter *format = [[NSDateFormatter alloc] init];
//        [format setDateFormat:@"yyyy.MM.dd"];

         NSLog(@"sender class%@",[sender class]);

        NSLog(@"indexpath%@",sender.indexPath);
        //插入开始时间
         NSLog(@"secyion&row %ld%ld",sender.indexPath.section,sender.indexPath.row);
        if (sender.indexPath.section == 1 && sender.indexPath.row == 1) {

            //在主药盒表的开始时间中插入当前datepick选择的时间
            //用coredata手动创建的实体类实例化的_drugMaster对象存储datePick的当前时间nslog结果为null
    self.drugMaster.startAt                                  = datePicker.date;
            NSLog(@"_drugMaster.startAt%@",self.drugMaster.startAt);



//          刷新section
//            NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:1];
//            [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
            //刷新cell
            NSIndexPath *indexPath=[NSIndexPath indexPathForRow:1 inSection:1];

            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];

        }
        /**
         *  插入服药时间
         *
         *  @param sender.indexPath.row 第三个section
         *
         *  @return 第二个row之后的每个row
         */
        
        
        else if (sender.indexPath.section == 2){
            if (sender.indexPath.row >= 1 && sender.indexPath.row <= 8) {
                self.drugFlowing.uid = [self.timeFormatter stringFromDate:datePicker.date];

            }
            //          刷新section
            NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:2];
            [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        }
        
        //插入结束时间

        else if (sender.indexPath.section == 3 && sender.indexPath.row == 0) {
            //在主药盒表的结束时间中插入当前datepick选择的时间
    self.drugMaster.stopAt                                   = datePicker.date;

            //            NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:1];
            //            [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
            //刷新结束时间那一行
            NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:3];

            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];

        }





//        [_timeButton setTitle:[format stringFromDate:datePicker.date] forState:UIControlStateNormal];

        [self hideViewWithAnimation:toolBar];

        [self hideViewWithAnimation:datePicker];

        [self.view sendSubviewToBack:self.fatherView];
    }

}
//显示动画
- (void)showViewWithAnimation:(UIView *)view YPostion:(float)yPosition
{
    CGRect rect_origin                                       = view.frame;
    rect_origin.origin.y                                     = [UIScreen mainScreen].bounds.size.height;
    view.frame                                               = rect_origin;
    //    view.alpha = 0.5f;

    [UIView animateWithDuration:0.5f animations:^{
    CGRect rect_current                                      = view.frame;
    rect_current.origin.y                                    = yPosition;
    view.frame                                               = rect_current;
        //        view.alpha = 1.0f;
    } completion:^(BOOL finished){

    }];
}

//隐藏动画
- (void)hideViewWithAnimation:(UIView *)view
{
    [UIView animateWithDuration:0.5f animations:^{
    CGRect rect_current                                      = view.frame;
    rect_current.origin.y                                    = ([UIScreen mainScreen].bounds.size.height);
    view.frame                                               = rect_current;
    } completion:^(BOOL finished){
        [view setHidden:YES];
    }];
}
#pragma mark – lazy loading

-(NSDateFormatter *)dateFormatter{

    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc]init];
        [_dateFormatter setDateFormat:@"yyyy.MM.dd"];
    }
    return _dateFormatter;
}

-(NSDateFormatter *)timeFormatter{
    
    if (!_timeFormatter) {
        _timeFormatter = [[NSDateFormatter alloc]init];
        [_timeFormatter setDateFormat:@"MM.dd"];
    }
    return _timeFormatter;

}

-(UIImage *)medicineImage{

    if (!_medicineImage) {
    _medicineImage                                           = [[UIImage alloc]init];
    }
    return _medicineImage;
}

-(DrugMasterEntity *)drugMaster{

    if (!_drugMaster) {// 创建托管对象，并指明创建的托管对象所属实体名
    _drugMaster                                              = [NSEntityDescription insertNewObjectForEntityForName:@"DrugMasterEntity" inManagedObjectContext:app.managedObjectContext];
    }
    return _drugMaster;
}
-(DrugFlowingEntity *)drugFlowing{

    if (!_drugFlowing) {
        _drugFlowing                                              = [NSEntityDescription insertNewObjectForEntityForName:@"DrugFlowingEntity" inManagedObjectContext:app.managedObjectContext];
    }
    return _drugFlowing;
}
-(UIView *)fatherView{

    if(!_fatherView){
    _fatherView                                              = [[UIView alloc]initWithFrame:CGRectMake(0,0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
        // [_fatherView setBackgroundColor:[UIColor redColor]];
    }

    return _fatherView;

}

-(UIButton *)bottomButton{

    if(!_bottomButton){
    _bottomButton                                            = [[UIButton alloc]init];
    }

    return _bottomButton;

}

-(NSFetchedResultsController *)fetchedController{

    if (!_fetchedController) {
        
        return _fetchedController;
    }
        //实例化一个请求
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    //添加一个要查询的实体的描述对象
    
    return _fetchedController;
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/*
 #pragma mark - Navigation

 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
